package wqh.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import wqh.dao.Dao;

import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by TsinghuaWoo on 2016/12/29.
 */
public class DaoImpl<T> extends HibernateDaoSupport implements Dao<T> {

    private Class<T> entityClass;

    @Autowired
    public void setSessionFactory0(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }

    @SuppressWarnings("unchecked")
    public DaoImpl() {
        entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Class<T> getEntityClass() {
        return entityClass;
    }

    public void setEntityClass(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void save(T entity) {
        this.getHibernateTemplate().save(entity);
    }

    public void update(T entity) {
        this.getHibernateTemplate().update(entity);
    }

    public void clear() {
        this.getHibernateTemplate().clear();
    }

    public void flush() {
        this.getHibernateTemplate().flush();
    }

    public void delete(T entity) {
        this.getHibernateTemplate().delete(entity);
    }

    public void deleteAll() {
        String name = entityClass.getSimpleName();
        String hql = "DELETE " + name;
        Session session = this.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(hql);
        query.executeUpdate();

    }

    public List<T> findAll() {
        Session session = this.getSessionFactory().getCurrentSession();
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<T> criteria = builder.createQuery(entityClass);
        Root<T> tRoot = criteria.from(entityClass);
        criteria.select(tRoot);
        return session.createQuery(criteria).getResultList();
    }

    public T findById(Long id) {
        return this.getHibernateTemplate().get(entityClass, id);
    }


}
